import { login, getUserInfo } from '@/api/login'
import { Message } from 'element-ui'
import router from '@/router/index'

const state = {
  token: window.sessionStorage.getItem('token'),
  roles: [],
  userInfo: {},
  permissionTable: [],
  menuKeys: []
}

const mutations = {
  /* 添加token */
  addToken (state, token) {
    state.token = token
  },
  /* 添加角色 */
  addRole (state, userRole) {
    state.roles = userRole
  },
  /* 添加个人信息 */
  addUserInfo (state, userInfo) {
    state.userInfo = userInfo
  },
  // 添加权限
  addPermission (state, permission) {
    state.permissionTable = permission
  },
  /* 移除token */
  removeToken (state) {
    window.sessionStorage.clear()
    state.roles = []
    location.reload()
  }
}

const actions = {
  /* 用户登录 */
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        commit('addToken', res.data)
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  },
  /* 获取用户个人信息 */
  getUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        const roles = res.data.roles
        if (roles.length === 0) {
          window.sessionStorage.clear()
          router.push('/login')
          Message.error({ message: '请分配角色' })
          return false
        }
        commit('addRole', roles)
        commit('addPermission', res.data.paraNameList || [])
        commit('addUserInfo', res.data)
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  },
  /* 退出登录 */
  logout ({ commit }) {
    commit('removeToken')
  }
}

const getters = {
  /* 获取token */
  getToken (state) {
    return state.token
  },
  /* 获取角色 */
  getRoles (state) {
    return state.roles
  },
  // 获取权限表
  getPermission (state) {
    return state.permissionTable
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
